#-*- coding:utf-8 -*-
import numpy as np
import cv2 as cv
import sys
import os
import math
import time
import shutil
from threading import Thread

cpArr = []

# 复制加载错误文件
def chkImg(file, out):
    if (not os.path.exists(out)):
        print(file, ' 复制ing')
        time.sleep(0.2)
        Thread(target=shutil.copy, args=[file, out]).start()
        cpArr.append(out)

# 获取thumb图
def getThImg(file, out):
    # 读取
    # org = cv.imread(file)
    org = dealZhImg(file)
    # 裁剪，4个点位 上下左右
    h, w = org.shape[:2]
    h, w = int(h), int(w)
    dlt = int(math.fabs((w - h) / 2))
    if (w > h):
        p = [0, h, dlt, dlt + h]
    else:
        p = [dlt, dlt + w, 0, w]
    spr = org[p[0]:p[1], p[2]:p[3]]
    # 缩放
    scl = cv.resize(spr, (100, 100), interpolation=cv.INTER_LINEAR)
    # 保存图片
    # cv.imwrite(out, scl)
    tmp = filePath.split('.')
    ext = '.'+ tmp.pop()
    cv.imencode(ext, scl)[1].tofile(outPath)
    time.sleep(0.2)

# rnm，解决中文路径
def dealZhImg(filePath):
    return cv.imdecode(np.fromfile(filePath, dtype=np.uint8), -1)


if __name__ == '__main__':
   
    objName = input("输入项目名：")
    folder = input("输入文件夹名：")

    if not (objName and folder):
        print('输入有空值！')
        exit(0)
    print('默认输出文件夹为\"输入文件夹-th\"！')

    pathName = '../{0}/{1}'.format(objName, folder)
    outPathName = '../{0}/{1}-th'.format(objName, folder)

    for root, dirs, files in os.walk(pathName):
        rt = root.replace('\\','/')
        th_rt = outPathName
        print(rt, th_rt)
        print(dirs)
        print(files, len(files))
        if (not os.path.exists(th_rt)):
            os.makedirs(th_rt)
        if(len(files) > 0):
            for file in files:
                filePath = rt + '/' + file
                outPath = th_rt + '/' + file
                if(file.split('.').pop() == 'gif'):
                    chkImg(filePath, outPath)
                # print(filePath, outPath)
                if(not os.path.exists(outPath)):
                    try:
                        print(file, ' 转换ing')
                        getThImg(filePath, outPath)
                    except:
                        chkImg(filePath, outPath)
    print('需要手动处理的文件')
    print(cpArr)
